package es.deusto.ingenieria.tesoroaventurero;

import java.awt.Point;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import es.deusto.ingenieria.is.formulation.State;
import es.deusto.ingenieria.is.search.blind.BreadthFSwithLog;
import es.deusto.ingenieria.tesoroaventurero.Escenario;

public class MainProgram {

	private static List<Point> gemas;
	
	
	

    public static void main (String [] args){
		try{
			gemas = new LinkedList<Point>();
			TesoroAventureroProblem problem = new TesoroAventureroProblem();
			Escenario initialState = (Escenario) new EscenarioXMLReader("data/treasureadventure-1.xml").getInformation();
			problem.addInitialState( new State(initialState));
			
			for (int i = 0; i < ((Escenario)initialState).getCasillas().length; i++){
				for (int j = 0; j < ((Escenario)initialState).getCasillas()[0].length; j++){
					if (initialState.getCasilla(j, i).isGema()){
						gemas.add(new Point(i, j));
						
					}		
				}
			}
			
		
			Collections.sort(gemas,new GemaComparator());
			
			while (gemas.size() != 0){
				Personaje p = new Personaje();
				p.x = gemas.get(0).y;
				p.y = gemas.get(0).x;
				Escenario e = new Escenario(initialState.getCasillas(), initialState.getTesoro().x, initialState.getTesoro().y);
				e.setPersonaje(p);
				if (!problem.getFinalStates().isEmpty())
					problem.getFinalStates().remove(0);
				problem.addFinalState(new State(e));
				Thread.sleep(900);
				problem.solve(BreadthFSwithLog.getInstance());
				e.getCasilla(gemas.get(0).y, gemas.get(0).x).setGema(true);
				gemas.remove(0);
				problem.getInitialStates().remove(0);
				problem.addInitialState(new State(e));
			}
			
			Personaje pT = new Personaje();
			Escenario e2 = new Escenario(initialState.getCasillas(), initialState.getTesoro().x, initialState.getTesoro().y);
			pT.x = initialState.getTesoro().x;
			pT.y = initialState.getTesoro().y;
			e2.setPersonaje(pT);
			if (!problem.getFinalStates().isEmpty())
				problem.getFinalStates().remove(0);
			problem.addFinalState(new State(e2));
			Thread.sleep(900);
			problem.solve(BreadthFSwithLog.getInstance());
			
			
		}catch (Exception ex){
			System.err.println("% [MainProgram] Error: " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}


